package com.gss.plugin.oauth2.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gss.entity.R;
import com.gss.entity.enums.ConstantEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author DYang
 * @date 2023/7/21
 * 权限不足异常
 */
@Slf4j
public class ResourceAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 自定义返回格式内容
        R<Object> res = R.error(ConstantEnum.TOKEN_MISS);
        res.setMsg("认证过的用户访问无权限资源时的异常");
        res.setDesc(accessDeniedException.getMessage());

        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());// 权限不足403

        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(res));
        writer.flush();
        writer.close();

    }
}
